package com.workingpub.commons.jdbc.builder.internal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.workingpub.commons.jdbc.binding.ForeachEntry;
import com.workingpub.commons.jdbc.builder.BuildContext;
import com.workingpub.commons.jdbc.builder.LogicResolver;
import com.workingpub.commons.jdbc.builder.ResolverFactory;
import com.workingpub.commons.jdbc.builder.SqlParamBuilder;
import com.workingpub.commons.jdbc.builder.ognl.OgnlEvaluator;

@Service
public class ForeachResolver implements LogicResolver {

	@Autowired
	private ResolverFactory resolverFactory;

	@Override
	public List<Object> getContext(BuildContext buildContext, Object logicEntry) {
		if (logicEntry instanceof ForeachEntry) {
			ForeachEntry foreachEntry = (ForeachEntry) logicEntry;
			Iterable<?> values = OgnlEvaluator.evaluateIterable(foreachEntry.getCollection(),
					buildContext.getRootParameter(), buildContext.getOtherParameters());
			if (null != values) {
				Map<String, Object> localParams = new HashMap<String, Object>();
				List<Object> resultEntries = new ArrayList<Object>();
				resultEntries.add(foreachEntry.getOpen());
				for (Object item : values) {
					for (Object subEntry : foreachEntry.getContent()) {
						if (subEntry instanceof String) {
							localParams.clear();
							localParams.put(foreachEntry.getItem(), item);
							String sqlSegment = SqlParamBuilder.build((String) subEntry, buildContext, localParams,
									StringUtils.hasText(foreachEntry.getIndex())
											? Integer.valueOf(foreachEntry.getIndex()) : null);
							resultEntries.add(sqlSegment + foreachEntry.getSeparator());
						} else {
							resultEntries.addAll(resolverFactory.resolve(buildContext, subEntry));
						}
					}
				}
				resultEntries.add(foreachEntry.getClose());
				return resultEntries;
			}
		}
		return null;
	}

}
